import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useLoadStore } from '@/stores/counter'
import VueCookie from "vue-cookie";
const loadStore = useLoadStore()
import router from '@/router'
export const _axios = axios.create({
  // baseURL: 'http://cn-jn-lt-plustmp1.natfrp.cloud:62673/'
  baseURL: 'http://localhost:8080'
})

export const request = (url, method, params, callback) => {
  const axiosConfig = {
    url,
    method
  }
  const token=VueCookie.get('token')
  if (token){
    _axios.defaults.headers['token']=token
  }
  if (method === 'post') {
    const formData = new FormData()
    for (const key in params) {
      formData.append(key, params[key])
    }
    axiosConfig.data = formData
  } else {
    axiosConfig.params = params
  }
  loadStore.open()
  _axios.request(axiosConfig).then(response => {
    if (response.data.code === 200) {
      if (response.data.message) {
        ElMessage.success(response.data.message)
      }
      callback(response.data.content)
    } else {
      ElMessage.error(response.data.message)
      if (response.data.code===401){
          router.push("/login")
      }
    }
  }).catch(error => {
    console.dir(error)
  }).finally(() => {
    loadStore.close()
  })
}

export const get = (url, params, callback) =>
{ request(url, 'get', params, callback) }

export const post = (url, params, callback, formobj=null) => {
  if (formobj) {
    formobj.value.validate(valid => {
      if (valid) {
        request(url, 'post', params, callback)
      }
    })
  } else {
    request(url, 'post', params, callback)
  }
}
